package com.servlet;

import com.alibaba.fastjson.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/AjaxServlet")
public class AjaxServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        System.out.println("method:"+method);
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        System.out.println(name+" "+sex);

        //String locaDateTime = LocalDateTime.now().toString();
        Map<String,Object> map1 = new HashMap<String,Object>();
        map1.put("id",1001);
        map1.put("name","张三");
        map1.put("sex","男");

        Map<String,Object> map2 = new HashMap<>();
        map2.put("id",1002);
        map2.put("name","李四");
        map2.put("sex","女");

        List<Map<String,Object>> stuList = new ArrayList<>();
        stuList.add(map1);
        stuList.add(map2);

        //String jsonStr = "{\"name\":\"张三\",\"sex\":\"男\"}";

        //将java对象转为json字符串:jackson,Gson,fastjson
        System.out.println(stuList);
        //将数据转为json字符串
        String jsonStr =  JSONArray.toJSONString(stuList); //实体对象,map
        System.out.println(jsonStr);


        resp.setContentType("text/html;charset=utf-8");
        //获取输出流对象
        PrintWriter out = resp.getWriter();
        out.println(jsonStr);
        out.flush();
        out.close();

    }
}
